import {
    AlipayCircleOutlined,
    LockOutlined,
    MobileOutlined,
    TaobaoCircleOutlined,
    UserOutlined,
    WeiboCircleOutlined,
} from '@ant-design/icons';
import {
    LoginForm,
    ProConfigProvider,
    ProFormCaptcha,
    ProFormCheckbox,
    ProFormText,
    setAlpha,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Form, Input, message, Space, Tabs, theme } from 'antd';
import { createStyles } from 'antd-style';
import { useNavigate } from 'react-router-dom';
import { login } from '../api/request';
import { CSSProperties, useState } from 'react';
import { LoginType } from '../api/http.d';
import { jwtDecode } from "jwt-decode";

const useStyles = createStyles(({ token }) => {
    return {
        action: {
            marginLeft: '8px',
            color: 'rgba(0, 0, 0, 0.2)',
            fontSize: '24px',
            verticalAlign: 'middle',
            cursor: 'pointer',
            transition: 'color 0.3s',
            '&:hover': {
                color: token.colorPrimaryActive,
            },
        },
        lang: {
            width: 42,
            height: 42,
            lineHeight: '42px',
            position: 'fixed',
            right: 16,
            borderRadius: token.borderRadius,
            ':hover': {
                backgroundColor: token.colorBgTextHover,
            },
        },
        container: {
            display: 'flex',
            flexDirection: "row",
            height: '100vh',
            overflow: 'auto',
            position: 'relative'
        },
    };
});

type LoginDataType = 'phone' | 'account';

const Login = () => {
    const { styles } = useStyles();
    const navigate = useNavigate();

    const { token } = theme.useToken();
    const [loginType, setLoginType] = useState<LoginDataType>('account');

    const iconStyles: CSSProperties = {
        marginInlineStart: '16px',
        color: setAlpha(token.colorTextBase, 0.2),
        fontSize: '24px',
        verticalAlign: 'middle',
        cursor: 'pointer',
    };

    const { loading: loginLoding, run: loginRun } = useRequest(login, {
        manual: true,
        onSuccess: (data) => {
            if (data.code == 200) {
                localStorage.setItem("token", data.data as string);
                const decoded = jwtDecode(data.data as string);
                localStorage.setItem("user", JSON.stringify(decoded));
                navigate('/rag/project');
            } else {
                message.error(data.msg);
            }
        }
    })

    return (
        <div className={styles.container} >
            <div className='absolute flex top-4 left-4'>
                <img src="img/logo-v1.webp" style={{ height: 34 }} />
                <span className='text-[1.25rem] ml-4'>AI智能体平台</span>
            </div>

            <div style={{
                flex: '1',
                justifyContent: 'center',
                alignItems: 'center',
                backgroundImage: "url('img/logobg.png')",
                backgroundSize: '100% 100%',
                display: "flex",
                flexDirection: "column",
                minWidth: 500,
            }}>

                <img src="img/bg.svg" style={{ height: 280, animationDuration: '6s' }} className='animate-bounce h-[300px] mb-4' />

                <div className='text-[34px]'>开启智能新时代</div>
                <div className='text-[14px] mt-2'>智能 AI 助手：赋能未来的解决方案</div>
            </div>
            <div style={{ width: 500, display: 'flex', justifyContent: 'center' }}>
                <div
                    style={{
                        position: 'relative',
                        top: '40%',
                        transform: 'translateY(-40%)',
                        height: 500,
                        width: 600
                    }}
                >
                    <LoginForm
                        logo="img/logo-v1.webp"
                        title="AI智能体平台"
                        subTitle="AI智能体赋能未来的解决方案"
                        loading={loginLoding}
                        actions={
                            <Space>
                                <span className='text-[14px]'>
                                    其他登录方式
                                </span>
                                <AlipayCircleOutlined style={iconStyles} />
                                <TaobaoCircleOutlined style={iconStyles} />
                                <WeiboCircleOutlined style={iconStyles} />
                            </Space>
                        }
                        onFinish={(values: LoginType) => {
                            loginRun(values)
                        }}
                    >
                        <Tabs
                            centered
                            activeKey={loginType}
                            onChange={(activeKey) => setLoginType(activeKey as LoginDataType)}
                        >
                            <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
                            <Tabs.TabPane key={'phone'} tab={'手机号登录'} />
                        </Tabs>
                        {loginType === 'account' && (
                            <>
                                <ProFormText
                                    name="userName"
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <UserOutlined className={'prefixIcon'} />,
                                    }}
                                    placeholder={'用户名'}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入用户名!',
                                        },
                                    ]}
                                />
                                <ProFormText.Password
                                    name="password"
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <LockOutlined className={'prefixIcon'} />,
                                        strengthText:
                                            '密码应包含数字、字母和特殊字符，长度至少为8个字符',
                                        statusRender: (value) => {
                                            const getStatus = () => {
                                                if (value && value.length > 12) {
                                                    return 'ok';
                                                }
                                                if (value && value.length > 6) {
                                                    return 'pass';
                                                }
                                                return 'poor';
                                            };
                                            const status = getStatus();
                                            if (status === 'pass') {
                                                return (
                                                    <div style={{ color: token.colorWarning }}>
                                                        强度：中
                                                    </div>
                                                );
                                            }
                                            if (status === 'ok') {
                                                return (
                                                    <div style={{ color: token.colorSuccess }}>
                                                        强度：强
                                                    </div>
                                                );
                                            }
                                            return (
                                                <div style={{ color: token.colorError }}>强度：弱</div>
                                            );
                                        },
                                    }}
                                    placeholder={'密码'}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入密码！',
                                        },
                                    ]}
                                />
                            </>
                        )}
                        {loginType === 'phone' && (
                            <>
                                <ProFormText
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <MobileOutlined className={'prefixIcon'} />,
                                    }}
                                    name="mobile"
                                    placeholder={'手机号'}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入手机号！',
                                        },
                                        {
                                            pattern: /^1\d{10}$/,
                                            message: '手机号格式错误！',
                                        },
                                    ]}
                                />
                                <ProFormCaptcha
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <LockOutlined className={'prefixIcon'} />,
                                    }}
                                    captchaProps={{
                                        size: 'large',
                                    }}
                                    placeholder={'请输入验证码'}
                                    captchaTextRender={(timing, count) => {
                                        if (timing) {
                                            return `${count} ${'获取验证码'}`;
                                        }
                                        return <span className='text-[14px]'>获取验证码</span>;
                                    }}
                                    name="captcha"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入验证码！',
                                        },
                                    ]}
                                    onGetCaptcha={async () => {
                                        message.success('获取验证码成功！验证码为：1234');
                                    }}
                                />
                            </>
                        )}
                        <div
                            style={{
                                marginBlockEnd: 24,
                            }}
                        >
                            <ProFormCheckbox noStyle name="autoLogin">
                                自动登录
                            </ProFormCheckbox>
                            <a
                                style={{
                                    float: 'right',
                                    color: token.colorPrimary,
                                }}
                            >
                                忘记密码
                            </a>
                        </div>
                    </LoginForm>
                </div>
            </div>
        </div>
    );
};

export default Login;